<template>
    <div class="user-activity-container">
      <h2>用户活动数据统计</h2>
      <div v-if="isLoading" class="loading">数据加载中...</div>
      <div v-else-if="hasError" class="error">
        <div v-if="errorMessage">{{ errorMessage }}</div>
        <div v-else>数据获取失败，请稍后重试！</div>
      </div>
      <div v-else>
        <!-- 注册数量统计卡片 -->
        <div class="card-container">
          <div class="card-item">
            <span class="card-value">{{ registeredHospitalCount }}</span>
            <span class="card-label">注册医院数</span>
          </div>
          <div class="card-item">
            <span class="card-value">{{ registeredDoctorCount }}</span>
            <span class="card-label">注册医生数</span>
          </div>
          <div class="card-item">
            <span class="card-value">{{ registeredPatientCount }}</span>
            <span class="card-label">注册患者数</span>
          </div>
        </div>
        <!-- 图表区域 -->
        <div class="chart-container">
          <div v-if="activityRateData.length > 0" id="activityRateChart" class="chart"></div>
          <div v-else class="no-data-message">暂无活跃度数据</div>
          <div v-if="registeredUserData.length > 0" id="registeredUserChart" class="chart"></div>
          <div v-else class="no-data-message">暂无注册用户数数据</div>
        </div>
      </div>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, onMounted, nextTick, onUnmounted } from 'vue';
  import axios from 'axios';
  import * as echarts from 'echarts';
  
  // 定义注册数量相关的响应式变量
  const registeredHospitalCount = ref(0);
  const registeredDoctorCount = ref(0);
  const registeredPatientCount = ref(0);
  
  // 定义活跃度和注册用户数相关的数组，用于图表数据
  const activityRateData = ref<{ name: string; data: number[] }[]>([
    { name: '医院活跃度', data: [] },
    { name: '医生活跃度', data: [] },
    { name: '患者活跃度', data: [] }
  ]);
  
  const registeredUserData = ref<{ name: string; data: number[] }[]>([
    { name: '医院注册数', data: [] },
    { name: '医生注册数', data: [] },
    { name: '患者注册数', data: [] }
  ]);
  
  // 定义加载状态和错误状态的响应式变量
  const isLoading = ref(true);
  const hasError = ref(false);
  const errorMessage = ref('');
  
  // 添加接口类型定义
  interface UserActivity {
    hospitalActivityRate: number;
    doctorActivityRate: number;
    patientActivityRate: number;
    month: string;
  }
  
  interface RegistrationGrowth {
    hospitalGrowth: number;
    doctorGrowth: number;
    patientGrowth: number;
    month: string;
  }
  
  onMounted(async () => {
    try {
      // 添加测试数据
      // 1. 注册总数测试数据
      registeredHospitalCount.value = 150;
      registeredDoctorCount.value = 500;
      registeredPatientCount.value = 1000;

      // 2. 活跃度测试数据
      activityRateData.value = [
        {
          name: '医院活跃度',
          data: [85, 87, 89, 90, 92, 95]
        },
        {
          name: '医生活跃度',
          data: [75, 78, 80, 82, 85, 88]
        },
        {
          name: '患者活跃度',
          data: [65, 68, 70, 73, 75, 78]
        }
      ];

      // 3. 注册增长测试数据
      registeredUserData.value = [
        {
          name: '医院注册数',
          data: [10, 15, 20, 25, 30, 35]
        },
        {
          name: '医生注册数',
          data: [50, 60, 70, 80, 90, 100]
        },
        {
          name: '患者注册数',
          data: [100, 120, 150, 180, 200, 250]
        }
      ];

      isLoading.value = false;
      await nextTick();

      // 初始化图表
      if (activityRateData.value[0].data.length > 0) {
        initActivityRateChart();
      }
      
      if (registeredUserData.value[0].data.length > 0) {
        initRegisteredUserChart();
      }

    } catch (error: any) {
      console.error('初始化失败', error);
      hasError.value = true;
      errorMessage.value = '数据加载失败，请稍后重试';
      isLoading.value = false;
    }
  });
  
  // 修改月份标签生成函数
  const getMonthLabels = (): string[] => {
    const labels: string[] = [];
    const now = new Date();
    for (let i = 5; i >= 0; i--) {
      const d = new Date();
      d.setMonth(now.getMonth() - i);
      const month = d.getMonth() + 1;
      const year = d.getFullYear();
      labels.push(`${year}年${month}月`);
    }
    return labels;
  };
  
  // 初始化用户活跃度占比图表
  const initActivityRateChart = () => {
    const chartDom = document.getElementById('activityRateChart');
    if (!chartDom) {
      console.error('找不到活跃度图表DOM元素');
      return;
    }
  
    const myChart = echarts.init(chartDom);
    const monthLabels = getMonthLabels();
    
    const option = {
      title: {
        text: '用户活跃度趋势',
        subtext: '最近6个月数据',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        formatter: function (params: any[]) {
          return params[0].name + '<br/>' +
            params.map(item => `${item.seriesName}: ${item.value.toFixed(2)}%`).join('<br/>');
        }
      },
      legend: {
        data: activityRateData.value.map(item => item.name),
        bottom: 0
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '10%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: monthLabels
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          formatter: '{value}%'
        },
        max: 100
      },
      series: activityRateData.value.map((item, index) => ({
        name: item.name,
        type: 'line',
        smooth: true,
        data: item.data,
        itemStyle: {
          color: ['#009999', '#91cc75', '#fac858'][index]
        },
        areaStyle: {
          opacity: 0.1
        },
        emphasis: {
          focus: 'series'
        },
        markPoint: {
          data: [
            { type: 'max', name: '最大值' },
            { type: 'min', name: '最小值' }
          ]
        }
      }))
    };
    myChart.setOption(option);
    
    window.addEventListener('resize', () => {
      myChart.resize();
    });
  };
  
  // 初始化注册用户数图表
  const initRegisteredUserChart = () => {
    const chartDom = document.getElementById('registeredUserChart');
    if (!chartDom) {
      console.error('找不到注册数图表DOM元素');
      return;
    }
  
    const myChart = echarts.init(chartDom);
    const monthLabels = getMonthLabels();
    
    const option = {
      title: {
        text: '注册用户数趋势',
        subtext: '最近6个月数据',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        formatter: function (params: any[]) {
          return params[0].name + '<br/>' +
            params.map(item => `${item.seriesName}: ${item.value}`).join('<br/>');
        }
      },
      legend: {
        data: registeredUserData.value.map(item => item.name),
        bottom: 0
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '10%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: monthLabels
      },
      yAxis: {
        type: 'value'
      },
      series: registeredUserData.value.map((item, index) => ({
        name: item.name,
        type: 'line',
        smooth: true,
        data: item.data,
        itemStyle: {
          color: ['#f90', '#f66', '#99d2dd'][index]
        },
        areaStyle: {
          opacity: 0.1
        },
        emphasis: {
          focus: 'series'
        },
        markPoint: {
          data: [
            { type: 'max', name: '最大值' },
            { type: 'min', name: '最小值' }
          ]
        }
      }))
    };
    myChart.setOption(option);
    
    window.addEventListener('resize', () => {
      myChart.resize();
    });
  };
  
  // 添加组件卸载时的清理函数
  onUnmounted(() => {
    const charts = [
      document.getElementById('activityRateChart'),
      document.getElementById('registeredUserChart')
    ];
    
    charts.forEach(chart => {
      if (chart) {
        const instance = echarts.getInstanceByDom(chart);
        if (instance) {
          instance.dispose();
        }
      }
    });
  });
  </script>
  
  <style scoped>
  .user-activity-container {
    border: 1px solid #ccc;
    border-radius: 5px;
    padding: 20px;
    margin: 20px;
  }
  
  .loading {
    color: gray;
    text-align: center;
  }
  
  .error {
    color: red;
    text-align: center;
  }
  
  .card-container {
    display: flex;
    justify-content: space-around;
    margin-bottom: 20px;
  }
  
  .card-item {
    background-color: #f9f9f9;
    border-radius: 5px;
    padding: 20px;
    text-align: center;
    width: 20%;
  }
  
  .card-value {
    font-size: 36px;
    color: #009999;
    margin-bottom: 10px;
  }
  
  .chart-container {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    margin: 20px 0;
  }
  
  .chart {
    width: 48%;
    height: 400px !important;
    border: 1px solid #ccc; 
    background-color: #f9f9f9;
    margin: 10px 0;
  }
  
  .no-data-message {
    color: gray;
    text-align: center;
    width: 48%;
  }
  </style>